﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Maxleaf.EDI.API.Contract.Client.Parameters;
using Maxleaf.EDI.Domain;
using Maxleaf.EDI.Domain.EDI;

namespace Maxleaf.EDI.Core.Handlers.QueryHandlers
{
    public class AuthenticateQueryHandler : IQueryHandler<AuthenticateParameters,AuthenticateResult>
    {
        private readonly IUnitOfWorkProvider unitOfWorkProvider;
        private readonly IRepository<User_DB> repository;

        public AuthenticateQueryHandler(
            IRepository<User_DB> repository,
            IUnitOfWorkProvider unitOfWorkProvider)
        {
            this.repository = repository;
            this.unitOfWorkProvider = unitOfWorkProvider;
        }

        public AuthenticateResult Handle(AuthenticateParameters parameters)
        {
            using (var unitOfWork = this.unitOfWorkProvider.GetEDIUnitOfWork())
            {
                if (string.IsNullOrEmpty(parameters.UserName))
                {
                    return new AuthenticateResult() { IsAuthorized = false };
                }

                var user = this.repository.GetSingleOrDefault(unitOfWork, o=>o.UserName==parameters.UserName);
                if (user == null)
                {
                    return new AuthenticateResult() { IsAuthorized = false };
                }

                var isAuthorized = user.Authenticate(parameters.Password);
                
                return new AuthenticateResult() { IsAuthorized = isAuthorized};
            }
        }
    }
}
